const axios = require('axios');
const express = require('express');
const app = express();
const url = require('url');
const util = require('util');
const getIps = require('./util/ip');
const { readJsonFileSync } = require('./util/file.js');
const Tool  = require('./util/tool.js');
const log = require('./util/log.js');
const { parse: kuaishouParse } = require('./parse/kuaishou');
const { parse: douyinParse } = require('./parse/douyin');
const { parse: kuaikanParse } = require('./parse/kuaikan');


let conf = readJsonFileSync("default.json");
log.log("config: " + JSON.stringify(conf));

app.get('/parse', (req, res) => {
	const parsedUrl = url.parse(req.url, true); // 第二个参数为true，则解析查询字符串
	log.info("解析目标url: " + parsedUrl.query.url)
	doDispense(parsedUrl.query.url, req, res);
});

const PORT = process.argv[2] | conf.serverPort || 7890;
app.listen(PORT, () => {
	let output = [];
	getIps().forEach(ip => {
		output.push(util.format(conf.doneHintFormatIten, ip, PORT));
	});
	log.log(util.format(conf.doneHintFormatContainer, output.join("")));
});

const domainMap = Tool.converTo (conf.domain);
const callMap = {
	"kuaishou": kuaishouParse,
	"douyin": douyinParse,
	"kuaikan": kuaikanParse
}

function doDispense(inputUrl, req, res) {
	res.setHeader('Content-Type', 'application/json');
	if (inputUrl) {
		const parsedUrl = url.parse(inputUrl, true); // 第二个参数为true，则解析查询字符串
		// log.log(parsedUrl)
		// log.log(callMap)
		// log.log("use host: ", parsedUrl.host)
		let type = domainMap[parsedUrl.host] || "default";
		let callback = callMap[type];
		let callbackType = typeof (callback);
		console.info("匹配解析信息{ host: " + (parsedUrl.host) + ", type: " + (type || "未知") + ", url: [" + inputUrl + "] }");
		if (callbackType === "function") {
			callback(inputUrl, req, res, conf);
		} else {
			let data = {
				status: 1,
				errMsg: "解析失败,不支持解析的url"
			}
			log.error(data);
			res.json(data);
		}
	} else {
		let data = {
			status: 1,
			errMsg: "解析失败,url为空"
		}
		log.error(data);
		res.json(data);
	}

}